package com.ganbo.ms.nio.group;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * 群聊系统服务端
 *
 * @author ganbo
 * @date 2022/11/15 9:14
 */
public class GroupChatServer {
    //定义相关属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    //构造器
    public GroupChatServer() {
        try {
            //得到选择器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //listenChannel
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //监听
    public void listen() {
        try {
            //循环处理
            while (true) {
//                int count = selector.select(2000);//监听两秒
                int count = selector.select();//监听两秒
                if (count > 0) { //有事件处理
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        //监听到accept连接事件
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);    //设置非阻塞
                            //将该sc注册到selector上面
                            sc.register(selector, SelectionKey.OP_READ);
                            //给出提示
                            System.out.println(sc.getRemoteAddress() + " 上线 ");
                        }

                        //通道发生read事件，即通道是可读的状态(就要从通道处理数据读到buffer里面)
                        if (key.isReadable()) {
                            //处理读
                            readData(key);
                        }

                        //当前的key 删除，防止重复处理
                        iterator.remove();

                    }
                } else {
                    System.out.println("等待中....");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }


    //读取客户端消息
    private void readData(SelectionKey key) {

        //取到关联的channel
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();
            //创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if (count > 0) {
                //把缓冲区的数据转成字符串
                String message = new String(buffer.array());
                //输出该消息
                System.out.println("from 客户端: " + message);

                //向其他的客户端转发消息(去掉自己)，专门写一个方法来处理
                sendInfoToOtherClients(message, channel);
            }

        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了..");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    //转发消息给其他客户(通道),这里要排除自己
    private void sendInfoToOtherClients(String message, SocketChannel self) throws IOException {

        System.out.println("服务器转发消息中...");
        //遍历 所有注册到selector上的SocketChannel,并排除self
        for (SelectionKey key : selector.keys()) {

            //通过key取出对应的 SocketChannel
            Channel targetChannel = key.channel();

            //排除自己,进行转发
            if (targetChannel instanceof SocketChannel && targetChannel != self) {

                //转型
                SocketChannel desc = (SocketChannel) targetChannel;
                //将msg存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
                //将buffer的数据写入通道
                desc.write(buffer);
            }

        }

    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
